package com.zsr.example.controller.front;

import com.alibaba.fastjson.JSONObject;
import com.zsr.example.service.MsmService;
import com.zsr.example.util.CommonUtil;
import com.zsr.example.util.RandomUtil;
import com.zsr.example.util.constants.ErrorEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 短信邮箱接口
 * @author zsr
 * @date 2021/6/18 23:13
 */
@RestController
@RequestMapping("/msmservice/msm")
@CrossOrigin //跨域
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送手机短信验证码
     * @param phone
     * @return
     */
    @GetMapping(value = "/sendMsg/{phone}")
    public JSONObject sendMsg(@PathVariable String phone) {
        String code = redisTemplate.opsForValue().get(phone);//从redis中取缓存
        if(!StringUtils.isEmpty(code)) return CommonUtil.successJson();

        code = RandomUtil.getFourBitRandom();//随机生成验证码
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = msmService.send(phone, "SMS_180051135", param);//填写阿里云模板
        if(isSend) {
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return CommonUtil.successJson();
        } else {
            return CommonUtil.errorJson(ErrorEnum.E_40001);
        }
    }

    @GetMapping(value = "/sendEmail/{toEmail}")
    public JSONObject sendEmail(@PathVariable String toEmail,
                                @RequestParam(value = "key", required = false) String key) {
        String code = redisTemplate.opsForValue().get(toEmail);//从redis中取缓存
        if (!StringUtils.isEmpty(code)) return CommonUtil.successJson();

        code = RandomUtil.getFourBitRandom();//随机生成验证码
            msmService.sendEmail(toEmail, code);
        if(!StringUtils.isEmpty(key)){
            toEmail=key+toEmail;
        }
        redisTemplate.opsForValue().set(toEmail, code, 5, TimeUnit.MINUTES);
        return CommonUtil.successJson();

    }
}